/*
 * @Description: 
 */
import axios from 'axios'

import { getToken, removeToken } from '@/utils/auth'
import { throttle } from '@/utils/index'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  timeout: 10 * 1000 // request timeout
  // timeout: 0,    // 不限制时间
})

// 请求监听
service.interceptors.request.use(
  config => {
    config.headers['token'] = getToken()
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应监听
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {

    if (error.response.status === 401) {
      // 节流函数 直接写throttle不起作用，得看看防抖节流的实现原理才能解答这个问题
      const throttleObj = {
        throttle: throttle(function () {
          ElMessage.warning('登录过期！请重新登录！')
          removeToken()
          location.reload()
          // router.replace('/login')
        })
      }
      throttleObj.throttle()
    } else if (error.response.status === 500) {
      ElMessage.error(error.response.data.message)
    }

    return Promise.reject(error)
  }
)

export default service